package com.booking.common.handler;

/**
 * @author Qikai.Lin
 * @date 2023/4/21
 */

import com.booking.common.enums.BookingErrorCode;
import com.booking.common.exception.BookingException;
import com.booking.common.dto.ClientResp;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.ObjectError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingRequestHeaderException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

import javax.servlet.http.HttpServletRequest;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.Optional;

@Slf4j
@ControllerAdvice
public class MyExceptionHandler {

    @ExceptionHandler(value = {HttpRequestMethodNotSupportedException.class})
    @ResponseBody
    public Object HttpRequestMethodNotSupportedException(final HttpRequestMethodNotSupportedException ex) {
        log.warn("url: {},HttpRequestMethodNotSupportedException:", getURI(), ex);
        return ClientResp.failure(BookingErrorCode.PARAM_ERROR);
    }

    @ExceptionHandler(value = {MethodArgumentTypeMismatchException.class})
    @ResponseBody
    public Object MethodArgumentTypeMismatchException(final MethodArgumentTypeMismatchException ex) {
        log.warn("url: {},MethodArgumentTypeMismatchException:", getURI(), ex);
        return ClientResp.failure(BookingErrorCode.PARAM_ERROR);
    }


    @ExceptionHandler(value = {MissingRequestHeaderException.class})
    @ResponseBody
    public Object missingRequestHeaderException(final MissingRequestHeaderException ex) {
        log.warn("url: {},MissingRequestHeaderException:", getURI(), ex);
        String errorMsg = ex.getParameter().getParameterName() + " parameter is missing";
        return ClientResp.failure(BookingErrorCode.PARAM_ERROR.getCode(), errorMsg);
    }


    @ExceptionHandler(value = {MethodArgumentNotValidException.class})
    @ResponseBody
    public Object handleMethodArgumentNotValidException(final MethodArgumentNotValidException ex) {
        log.warn("url: {},MethodArgumentNotValidException:", getURI(), ex);
        ObjectError objectError = ex.getBindingResult().getAllErrors().get(0);
        String errorMsg = Strings.isEmpty(objectError.getDefaultMessage()) ? BookingErrorCode.PARAM_ERROR.getMsg() : objectError.getDefaultMessage();
        return ClientResp.failure(BookingErrorCode.PARAM_ERROR.getCode(), errorMsg);
    }

    @ExceptionHandler(value = {BookingException.class})
    @ResponseBody
    public Object handleBusinessExceptions(final BookingException ex) {
        log.warn("url: {},BaseBusinessException.code: {} , msg: {}", getURI(), ex.getCode(), ex.getMsg());
        return ClientResp.failure(ex.getCode(), ex.getMsg());
    }


    @ExceptionHandler(value = {Exception.class})
    @ResponseBody
    public Object handleOtherExceptions(final Exception ex) {
        if (ex.getCause() instanceof SocketTimeoutException) {
            log.warn("url: {},SocketTimeoutException: {}", getURI(), ex);
            return ClientResp.failure(BookingErrorCode.TIME_OUT_ERROR);
        }
        if(ex.getCause() instanceof UnknownHostException){
            log.warn("url: {},SocketTimeoutException: {}", getURI(), ex);
            return ClientResp.failure(BookingErrorCode.UNKNOWN_HOST_ERROR);
        }
        log.error("url: {},Exception: {}", getURI(), ex);
        return ClientResp.failure(BookingErrorCode.UNKNOWN_HOST_ERROR);
    }

    /**
     * 处理http请求参数错误异常
     *
     * @param exception
     * @return
     */
    @ExceptionHandler(value = HttpMessageNotReadableException.class)
    @ResponseBody
    public Object httpMessageNotReadableExceptionHandler(HttpMessageNotReadableException exception) {
        log.warn("url: {},HttpMessageNotReadableException:", getURI(), exception);
        return ClientResp.failure(BookingErrorCode.UNKNOWN_HOST_ERROR);
    }

    /**
     * 处理http请求参数缺失异常
     *
     * @param exception
     * @return
     */
    @ExceptionHandler(value = MissingServletRequestParameterException.class)
    @ResponseBody
    public Object missingServletRequestParameterExceptionHandler(MissingServletRequestParameterException exception) {
        log.warn("url: {},MissingServletRequestParameterException: {}", getURI(), exception);
        return ClientResp.failure(BookingErrorCode.PARAM_ERROR);
    }


    /**
     * 处理域名解析异常
     *
     * @param exception
     * @return
     */
    @ExceptionHandler(value = UnknownHostException.class)
    @ResponseBody
    public Object unknownHostExceptionHandler(UnknownHostException exception) {
        log.warn("url: {},UnknownHostException: {}", getURI(), exception);
        return ClientResp.failure(BookingErrorCode.UNKNOWN_HOST_ERROR);
    }


    /**
     * 处理接口超时异常（包括feign超时与三方http超时）
     *
     * @param exception
     * @return
     */
    @ExceptionHandler(value = SocketTimeoutException.class)
    @ResponseBody
    public Object socketTimeoutExceptionHandler(SocketTimeoutException exception) {
        log.warn("url: {},SocketTimeoutException: {}", getURI(), exception);
        return ClientResp.failure(BookingErrorCode.TIME_OUT_ERROR);
    }

    private String getURI() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        assert attributes != null;
        HttpServletRequest request = attributes.getRequest();
        return Optional.ofNullable(request.getRequestURI()).orElse("");
    }

}

